import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h, onBeforeMount } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import agvReplace from '../replaceAgv.vue'
import agvForm from '../agvForm.vue'
import { websock } from '@/utils/webScoket'
import { cloneDeep } from "@pureadmin/utils";
import { ElButton } from 'element-plus';
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { jobList, CreateJob, jobDelete, Priority, jobDiscard, UpdateJobAgv, excelJob, CreateMove, CreateChargePileTask, CreateParking, MoveAgv, Initialize, GetAllStatusStorePlaceList } from '@/utils/api/dispatch/job'
import { GetStorePlaceList, GetAllStorePlaceList } from '@/utils/api/BasicManagement/locations'
import { GetAllAgv, ControlPower } from '@/utils/api/dispatch/agv'
import { GetAllStation } from '@/utils/api/dispatch/station'
import MenuFold from "@iconify-icons/ri/menu-fold-fill";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import EpArrowLeftBold from '@iconify-icons/ep/arrow-left-bold';
import EpArrowRightBold from '@iconify-icons/ep/arrow-right-bold';

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    const form = reactive({
        code: "",
        agvid: null,
        jobtype: null,
        status: "",
        dateRange: null,
        begin: "",
        end: "",
        startloc: "",
        endloc: "",
        outCode: "",
        trayCode: "",
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0,
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    // 目的地货位select
    let formCargo = ref([])

    let formCarry = ref([])

    // 搜索货位select
    let searchCargo = ref([])

    // 创建人select
    let userSelect = ref([])

    // 车辆select
    let agvSelect = ref([])

    // 站点select
    let stationSelect = ref([])

    // 状态
    function formatStatus(status) {
        const stateMap = {
            0: $t('job.created'),
            1: $t('job.inProgress'),
            2: $t('job.canceled'),
            3: $t('job.completed'),
            4: $t('job.abnormal'),
            5: $t('job.wait')
        }
        return stateMap[status]
    }

    const operationWidth = ref(80);

    const columns: any = ref([
        {
            label: $t('job.jobCode'),
            prop: "code",
            width: 140,
            align: "left",
            sortable: true
        },
        {
            label: $t('job.vehicleName'),
            prop: "AgvName",
            width: 120,
            align: "left"
        },
        {
            label: $t('job.jobType'),
            prop: "JobTypeName",
            width: 100,
            align: "left"
        },
        {
            label: $t('job.taskContent'),
            prop: "cn",
            width: 270,
            align: "left",
            cellRenderer: ({ row, props }) => (
                <div>
                    {row.jobtype === 1 && <span> {row.startloc} 到 {row.endloc}  [{row.stage === 1 ? '取货' : '卸货'}]</span>}
                    {row.jobtype !== 1 && <span>{row.TargetName}</span>}
                </div>
            ),
        },
        {
            label: $t('job.trayCode'),
            prop: "traycode",
            width: 140,
            align: "left"
            // sortable: true
        },
        {
            label: $t('job.priority'),
            prop: "topping",
            width: 100,
            align: "left",
            cellRenderer: ({ row, props }) => (
                <span>{row.topping ? $t('job.yes') : $t('job.no')}</span>
            ),
        },
        {
            label: $t('job.status'),
            prop: "status",
            width: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {formatStatus(row.status)}
                </el-tag>
            ),
            sortable: true
        },
        // {
        //   label: "新增人",
        //   prop: "userid",
        //   width: 100,
        //   align: "left"
        // },
        {
            label: $t('job.creationTime'),
            prop: "createtime",
            minWidth: 160,
            formatter: ({ createtime }) => dayjs(createtime).format("YYYY-MM-DD HH:mm:ss"),
            sortable: true
        },
        {
            label: $t('job.allocateTime'),
            prop: "allocationtime",
            minWidth: 160,
            formatter: ({ allocationtime }) =>
                !allocationtime ? '' : dayjs(allocationtime).format("YYYY-MM-DD HH:mm:ss")
            ,
            sortable: true
        },
        {
            label: $t('job.completionTime'),
            prop: "finishtime",
            minWidth: 160,
            formatter: ({ finishtime }) =>
                !finishtime ? '' : dayjs(finishtime).format("YYYY-MM-DD HH:mm:ss"),
            sortable: true
        },
        {
            label: $t('job.thirdPartyTaskCode'),
            prop: "outcode",
            width: 180,
            align: "left"
            // sortable: true
        },
        {
            label: $t('job.remarks'),
            prop: "note",
            minWidth: 200,
            align: "left",
            resizable: true,
            hide: false
        },
        {
            label: $t('job.operation'),
            fixed: "right",
            width: 80,
            slot: "operation",
            align: "left",
            resizable: true,
            headerRenderer: () => (
                <ElButton
                    type="info"
                    icon={operationWidth.value > 80 ? useRenderIcon(EpArrowRightBold) : useRenderIcon(EpArrowLeftBold)}
                    onClick={() => {
                        operationWidth.value = operationWidth.value > 80 ? 80 : 330;
                        columns.value[12].width = operationWidth.value
                    }}
                >
                    {$t('job.operation')}
                    {/* <IconifyIconOffline :icon="EpArrowRight" /> */}

                </ElButton>
            )
        }
    ])

    function tableReloading() {
        columns.value = [
            {
                label: $t('job.jobCode'),
                prop: "code",
                width: 140,
                align: "left",
                sortable: true
            },
            {
                label: $t('job.vehicleName'),
                prop: "AgvName",
                width: 120,
                align: "left"
            },
            {
                label: $t('job.jobType'),
                prop: "JobTypeName",
                width: 100,
                align: "left"
            },
            {
                label: $t('job.taskContent'),
                prop: "cn",
                width: 270,
                align: "left",
                cellRenderer: ({ row, props }) => (
                    <div>
                        {row.jobtype === 1 && <span> {row.startloc} 到 {row.endloc}  [{row.stage === 1 ? '取货' : '卸货'}]</span>}
                        {row.jobtype !== 1 && <span>{row.TargetName}</span>}
                    </div>
                ),
            },
            {
                label: $t('job.trayCode'),
                prop: "traycode",
                width: 140,
                align: "left"
                // sortable: true
            },
            {
                label: $t('job.priority'),
                prop: "topping",
                width: 100,
                align: "left",
                cellRenderer: ({ row, props }) => (
                    <span>{row.topping ? $t('job.yes') : $t('job.no')}</span>
                ),
            },
            {
                label: $t('job.status'),
                prop: "status",
                width: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.status)}>
                        {formatStatus(row.status)}
                    </el-tag>
                ),
                sortable: true
            },
            // {
            //   label: "新增人",
            //   prop: "userid",
            //   width: 100,
            //   align: "left"
            // },
            {
                label: $t('job.creationTime'),
                prop: "createtime",
                minWidth: 160,
                formatter: ({ createtime }) => dayjs(createtime).format("YYYY-MM-DD HH:mm:ss"),
                sortable: true
            },
            {
                label: $t('job.allocateTime'),
                prop: "allocationtime",
                minWidth: 160,
                formatter: ({ allocationtime }) =>
                    !allocationtime ? '' : dayjs(allocationtime).format("YYYY-MM-DD HH:mm:ss")
                ,
                sortable: true
            },
            {
                label: $t('job.completionTime'),
                prop: "finishtime",
                minWidth: 160,
                formatter: ({ finishtime }) =>
                    !finishtime ? '' : dayjs(finishtime).format("YYYY-MM-DD HH:mm:ss"),
                sortable: true
            },
            {
                label: $t('job.thirdPartyTaskCode'),
                prop: "outcode",
                width: 180,
                align: "left"
                // sortable: true
            },
            {
                label: $t('job.remarks'),
                prop: "note",
                minWidth: 200,
                align: "left",
                resizable: true,
                hide: false
            },
            {
                label: $t('job.operation'),
                fixed: "right",
                width: 80,
                slot: "operation",
                align: "left",
                resizable: true,
                headerRenderer: () => (
                    <ElButton
                        type="info"
                        icon={operationWidth.value > 80 ? useRenderIcon(EpArrowRightBold) : useRenderIcon(EpArrowLeftBold)}
                        onClick={() => {
                            operationWidth.value = operationWidth.value > 80 ? 80 : 330;
                            columns.value[12].width = operationWidth.value
                        }}
                    >
                        {$t('job.operation')}
                        {/* <IconifyIconOffline :icon="EpArrowRight" /> */}

                    </ElButton>
                )
            }
        ]
    }

    // 定义一个异步函数onSearch
    async function onSearch() {
        // 设置loading为true
        loading.value = true;
        if (!form.dateRange) {
            form.begin = ''
            form.end = ''
        }
        // 克隆form对象
        const searchData = cloneDeep(form)
        // 移除form中的dateRange
        delete searchData.dateRange
        // 将status转换为字符串
        searchData.status = searchData.status.toString()
        // 调用jobList函数，传入searchData，获取Content
        const { Content } = await jobList(searchData);
        // 将Content.Results赋值给newData
        let newData = Content.Results;
        // 将newData赋值给dataList
        dataList.value = newData;

        // 将Content.TotalCount赋值给pagination.total
        pagination.total = Content.TotalCount;
        // 将Content.PageSize赋值给pagination.pageSize
        pagination.pageSize = Content.PageSize;
        // 将Content.PageNumber + 1赋值给pagination.currentPage
        pagination.currentPage = Content.PageNumber + 1;

        // 设置一个定时器，500毫秒后将loading设置为false
        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    //作业
    function openDialog(title = '作业') {
        addDialog({
            title: $t('job.addHandling'),
            props: {
                formInline: {
                    startLocId: null,
                    endLocId: null,
                    agvId: null,
                    locState: 0,
                    emptyTray: 0,
                    batch: "",
                },
                formCargo: formCarry.value || [],
                agvSelect: agvSelect.value
            },
            // 设置宽度为45%
            width: "45%",
            // 设置可拖拽
            draggable: true,
            // 设置全屏图标
            fullscreenIcon: true,
            // 设置点击模态框时关闭
            closeOnClickModal: false,
            // 设置内容渲染器
            contentRenderer: () => h(elForm, { ref: formRef } as any),
            // 设置确认前的回调函数
            beforeSure: (done, { options }) => {
                // 获取表单引用
                const FormRef = formRef.value.getRef();
                // 获取当前数据
                const curData = options.props.formInline as FormItemProps;
                // 定义一个函数
                function chores() {
                    message(`新增成功`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        // console.log("curData", curData);
                        // 表单规则校验通过
                        CreateJob(curData).then(res => {
                            if (res.Code === 0) chores();
                        })
                    }
                });
            }
        })
    }

    // 移动、充电、停靠、取货架、托盘升降
    async function agvTask(title = '移动', fnType = 0) {
        // 站点列表 
        let { Content: station } = await GetAllStation({ status: 1, stationType: fnType })
        stationSelect.value = station
        let newTitle
        if (title === '移动') {
            newTitle = $t('job.mobileTask')
        } else if (title === '充电') {
            newTitle = $t('job.chargingTask')
        } else if (title === '返航') {
            newTitle = $t('job.returnMission')
        }

        // 弹框组件
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    target: null,
                    storePlaceId: null,
                    agvID: null,
                    type: null
                },
                type: fnType,
                agvSelect: agvSelect.value,
                stationSelect: stationSelect.value
            },
            width: `${fnType ? '20%' : '35%'}`,
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(agvForm, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message($t('form.operationSuccessful'), {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        let { target, agvID } = curData
                        // 表单规则校验通过
                        if (fnType === 0) {
                            // 移动
                            let data = { target, agvId: agvID }
                            CreateMove(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else if (fnType === 3) {
                            // 返航
                            let data = { agvID }
                            CreateParking(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else if (fnType === 2) {
                            // 充电
                            let data = { agvID }
                            CreateChargePileTask(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 更换车辆
    function replaceAgv(row) {
        addDialog({
            title: `更换车辆`,
            props: {
                formInline: {
                    type: 0,
                    agvId: null,
                },
                agvSelect: agvSelect.value,
            },
            width: "35%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(agvReplace, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message($t('form.operationSuccessful'), {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        curData.taskId = row.id
                        if (curData.type == 0) delete curData.agvId
                        // 表单规则校验通过
                        UpdateJobAgv(curData).then(res => {
                            if (res.Code === 0) chores();
                        })
                    }
                });
            }
        })
    }

    // 废弃
    function handleDiscard(row) {
        ElMessageBox.confirm(
            `是否确认废弃任务编号为${row.code}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            jobDiscard({ JobOnlyId: row.code }).then(res => {
                if (res.Code === 0) {
                    message($t('form.operationSuccessful'), { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 优先执行（取消优先）
    function taskPrior(row, type) {
        let title = type ? '是否优先执行此任务？' : '是否取消优先执行此任务？'
        ElMessageBox.confirm(
            title,
            $t('form.prompt'),
            {
                confirmButtonText: $t('form.confirm'),
                cancelButtonText: $t('form.cancel'),
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let data = { jobId: row.id, type }
            Priority(data).then(res => {
                if (res.Code === 0) {
                    message(`执行成功`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除任务编号为${row.code}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            jobDelete({ JobOnlyId: row.code }).then(res => {
                if (res.Code === 0) {
                    message(`您删除了任务编号为${row.code}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 初始化任务
    function initialization(row) {
        ElMessageBox.confirm(
            `是否确认初始化任务编号为${row.code}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            Initialize({ jobId: row.id }).then(res => {
                if (res.Code === 0) {
                    message(`您初始化了任务编号为${row.code}的这条数据`, { type: "success" });
                    onSearch();
                }
            })

            websock.send(JSON.stringify({ type: '初始化任务', data: row.id }));
        }).catch(() => { })
    }

    // 完成任务
    function complete(row) {
        ElMessageBox.confirm(
            `是否确认完成任务编号为${row.code}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            websock.send(JSON.stringify({ type: '完成任务', data: row.code, agvid: row.agvID ? row.agvID : 0 }));
            message(`提交成功`, { type: "success" });
        }).catch(() => { })
    }

    // 导出
    function exportExcel() {
        ElMessageBox.confirm(
            `是否确认导出数据?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            excelJob(form, '任务列表')
        }).catch(() => { })
    }

    const tableSize = ref('default')

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
        if (val > 10) {
            tableSize.value = 'small'
        } else {
            tableSize.value = 'default'
        }
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onBeforeMount(async () => {

    })

    onMounted(async () => {
        let { Content: agv } = await GetAllAgv({ state: 1 })
        agvSelect.value = agv

        // 目的地
        let { Content: from } = await GetStorePlaceList({ status: 1, attribute: 0 })
        formCargo.value = from


        // 搬运货位
        let { Content: carry } = await GetAllStatusStorePlaceList()
        //@ts-ignore
        formCarry.value = carry

        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        formCargo,
        userSelect,
        agvSelect,
        replaceAgv,
        taskPrior,
        exportExcel,
        handleDiscard,
        searchCargo,
        agvTask,
        initialization,
        complete,
        operationWidth,
        tableReloading,
        tableSize
    }
}